package com.card.user;

import java.util.List;
import java.util.Random;

import com.card.admin.pojo.Admin;
import com.card.admin.pojo.AdminManager;
import com.card.log.LogType;
import com.card.log.LogUtils;
import com.card.main.CardOnline;
import com.card.setting.GameSetting;
import com.card.user.UserCurrency.CurrencyKind;
import com.google.common.collect.Lists;
import com.xiaoao.net.db.DBManager;
import com.xiaoao.net.db.Entity;
import com.xiaoao.net.db.FilterOperator;
import com.xiaoao.net.db.Key;
import com.xiaoao.net.db.Query;
import com.xiaoao.net.db.Query.FilterPredicate;
import com.xiaoao.net.global.Global;
import com.xiaoao.net.utils.PrimaryKey;

/**
 * 用户工具类
 * 
 * @author xiaoaogame
 *
 */
public class UserUtils {
	// 表名
	public static final String T_USER_KEY = "userkey";
	public static final String T_USER_DATA = "userdata";
	// 属性名
	public static final String P_USER_KEY = "userkey";

	/**
	 * 根据imei获取玩家数据
	 * 
	 * @param username
	 * @return
	 */
	public static User getUserByImei(String imei) {
		String primaryKey = getPrimarykey(imei);
		// 从数据库获取玩家数据
		Entity entity = DBManager.getInstance().getEntityFromDB(new Key(T_USER_DATA, primaryKey));
		User user = entity == null ? createUser(primaryKey) : new User(entity);
		user.initBase();
		// 检查玩家邮件系统
		user.userMail().checkUserMail();
		// 登录检查
		user.loginChk();
//		System.out.println("imei" + imei);
		user.setUsername(imei);
		UserLogic.getInstance().chkSameUserLogin(user.getPrimaryKey());
		UserManager.getInstance().addUser(user);
		user.Store();

		return user;
	}
	
	//玩家用户
	public static List<User> getUsers(int adminid) {
		List<User> ads = Lists.newArrayList();

		List<Entity> entityList = getEntityByGroup(adminid);
		for (Entity entity : entityList) {
			ads.add(new User(entity));
		}
		return ads;
	}
	//玩家用户
	public static List<Entity> getEntityByGroup(int adminid) {
		System.out.println(adminid+"*************");
		Admin adminById = AdminManager.getInstance().getAdminById(adminid+"");
		Query query = new Query(T_USER_DATA);
		if (adminById.getGroup() != 1) {
			int parseInt = 0;
			if (adminById.getName() != null) {
				 parseInt =  Integer.parseInt(adminById.getName());
			}
			query.addFilter(new FilterPredicate(StringParam.FatherId, FilterOperator.EQUAL, parseInt));
		} else {
			query.addFilter(new FilterPredicate(StringParam.FatherId, FilterOperator.GREATER_THAN_OR_EQUAL, 0));
		}
		query.setLimit(10000);
		List<Entity> entityList = DBManager.getInstance().queryEntity(query);
		return entityList;
	}
	
	//俱乐部成员
	public static List<User> getJulebuUsers(String guanliyuanid) {
		List<User> ads = Lists.newArrayList();
		
		List<Entity> entityList = getEntityByJulebu(guanliyuanid);
		for (Entity entity : entityList) {
			ads.add(new User(entity));
		}
		return ads;
	}
	//俱乐部成员
	public static List<Entity> getEntityByJulebu(String guanliyuanid) {
		System.out.println(guanliyuanid+"*************");
		Query query = new Query(T_USER_DATA);
		
		query.addFilter(new FilterPredicate(StringParam.Julebuid, FilterOperator.EQUAL, guanliyuanid));
		query.addFilter(new FilterPredicate(StringParam.Julebustate, FilterOperator.NOT_EQUAL, 0));
		
		query.setLimit(10000);
		List<Entity> entityList = DBManager.getInstance().queryEntity(query);
		return entityList;
	}
	
	


	/**
	 * 创建用户
	 * 
	 * @param primaryKey
	 * @return
	 */
	private static User createUser(String primaryKey) {
		Entity entity = new Entity(T_USER_DATA, primaryKey);
		User user = new User(entity);
		user.userCurrency().add(CurrencyKind.Diamonds, GameSetting.getInstance().getInitGold());
		user.Store();

		LogUtils.addSpendLog(user, LogType.Init, GameSetting.getInstance().getInitGold());
		return user;
	}

	/**
	 * 根据imei获取服务器分配的主键,如果找不到就创建主键
	 * 
	 * @param username
	 * @return
	 */
	private static String getPrimarykey(String username) {
		Entity entity = DBManager.getInstance().getEntityFromCache(new Key(T_USER_KEY, username));
		if (entity == null) {
			// 第一次登陆，创建一个唯一
			String primaryKey = randomUserId();
			entity = new Entity(T_USER_KEY, username);
			entity.setProperty(P_USER_KEY, primaryKey);
			DBManager.getInstance().saveOrUpdate(entity);
		}
		return entity.getProperty(P_USER_KEY).toString();
	}

	/**
	 * 根据主键获取用户
	 * 
	 * @param primaryKey
	 * @return
	 */
	public static User getUserByPrimaryKey(String primaryKey) {
		User user = UserManager.getInstance().getUserByKey(primaryKey);
		if (user == null) {
			// 根据
			// 从数据库获取玩家数据
			Entity entity = DBManager.getInstance().getEntityFromDB(new Key(T_USER_DATA, primaryKey));
			if (entity != null) {
				user = new User(entity);
				user.initBase();
				return user;
			}
		}
		// Global.logErrorMessage("没有找到玩家："+primaryKey);
		return user;
	}

	public static String randomUserId() {
		int userId = new Random().nextInt(600000) + 300000;
		while (isExist(userId)) {
			userId = new Random().nextInt(600000) + 300000;
		}
		return String.valueOf(userId);
	}

	private static boolean isExist(int userId) {
		String primaryKey = String.valueOf(userId);
		User user = UserManager.getInstance().getUserByKey(primaryKey);
		if (user == null) {
			Entity entity = DBManager.getInstance().getEntityFromDB(new Key(T_USER_DATA, primaryKey));
			if (entity == null) {
				return false;
			}
		}
		return true;
	}
}
